package https;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import https.callback.BaseCommonCallback;
import common.Constant;
import https.bean.InterNetControllerBean;
import https.callback.BaseUploadCallback;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.SignatureUtil;

/**
 * Created by Administrator on 2017/3/14.
 */

public class UpLoadFileController {

    private static final String TAG = "UpLoadFileController";
    private Callback.Cancelable post;

    public UpLoadFileController(final Context context, final String url, final Handler handler, final HashMap<String, ?> dataMap, File file, final int flag) {
        MyLogUtils.e(TAG,url);

        String token = SPUtils.getSharedPreferences().getString(Constant.TOKEN, "");
        RequestParams requestParams = new RequestParams(url);
        String random = SignatureUtil.GetRandom(32);
        final String timeStamp = SignatureUtil.GetTimeStamp();
        requestParams.addParameter("rdStr", random);
        requestParams.addParameter("timestamp", timeStamp);
        requestParams.addParameter("token", token);
        HashMap<String, String> hashMap = new HashMap<>();
        if (dataMap != null) {
            if (dataMap.size() != 0) {
                Set set = dataMap.keySet();
                Iterator iter = set.iterator();
                while (iter.hasNext()) {
                    String key = (String) iter.next();
                    requestParams.addParameter(key, dataMap.get(key));
                    hashMap.put(key, String.valueOf(dataMap.get(key)));
                }
            }
        }
        hashMap.put("rdStr", random);
        hashMap.put("timestamp", timeStamp);
        hashMap.put("token", token);
        String phone = SPUtils.getSharedPreferences().getString(Constant.USER_ID,"");
        if (!TextUtils.isEmpty(phone)) {
            requestParams.addParameter("ac_id", phone);
            hashMap.put("ac_id", phone);
        }
        requestParams.addParameter("file", file);
        requestParams.addParameter("sign", SignatureUtil.getSignature(hashMap));
        requestParams.setConnectTimeout(5000);

        post = x.http().post(requestParams, new BaseUploadCallback(context) {
            @Override
            public void onSuccess(String result) {
                MyLogUtils.e(TAG, "onSuccess: " + result.toString());
                if (!BaseCommonCallback.stop) {
                    Message msg = new Message();
                    msg.what = Constant.ERROR_CODE_SUCCESS;
                    msg.arg1 = flag;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    MyLogUtils.e(TAG, "onSuccess: " + "stop");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Message msg = new Message();
                msg.what = Constant.ERROR_CODE_FAILD;
                InterNetControllerBean interNetControllerBean = new InterNetControllerBean();
                interNetControllerBean.setContext(context);
                interNetControllerBean.setUrl(url);
                interNetControllerBean.setFlag(flag);
                interNetControllerBean.setDataMap(dataMap);
                msg.obj = interNetControllerBean;
                if (!isNetworkAvailable(context)) {
                    //网络不可用时
                    interNetControllerBean.setNetworkError(true);
                } else {
                    interNetControllerBean.setNetworkError(false);
                }
                if (handler != null) {
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                    MyLogUtils.e(TAG,"取消上传了");
            }

            @Override
            public void onFinished() {
                Message msg = new Message();
                msg.what = Constant.ERROR_CODE_FINISH;
                msg.arg1 = flag;
                handler.sendMessage(msg);
            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                Message msg = new Message();
                float total1 = (float) (total / 1.0);
                float current1 = (float) (current / 1.0);
                float percent = current1 / total1;
                BigDecimal b = new BigDecimal(percent);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                MyLogUtils.e(TAG, "" + f1);
                msg.what = Constant.ERROR_CODE_UPLOADING;
                msg.obj = f1;
                handler.sendMessage(msg);
            }
        });
    }
    public void cancelUpload(){
        post.cancel();
    }
    /**
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }



    public static String getImageRemoteUrl(){
        //设置保存到服务器图片的名字
        return SignatureUtil.GetTimeStamp()+SignatureUtil.GetRandom(10);
    }

}
